package com.ruicar.afs.cloud.basic.commission.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.basic.commission.condition.CommissionCondition;
import com.ruicar.afs.cloud.basic.commission.vo.CommissionVo;
import com.ruicar.afs.cloud.basic.common.entity.*;
import com.ruicar.afs.cloud.basic.common.service.*;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.AddressTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.CalculateType;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.ProductAtomEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @author yaorui.zhang
 * @date 2020年8月24日 15:34:42
 */
@Slf4j
@RestController
@RequestMapping("/commission")
@AllArgsConstructor
public class CommissionController {

    private final BasicMainInfoService basicMainInfoService;
    private final BasicFinancialAgreementService basicFinancialAgreementService;
    private final BasicCarDetailsService basicCarDetailsService;
    private final BasicContractCustRelationService custRelationService;
    private final BasicCustBaseInfoService basicCustBaseInfoService;
    private final BasicCustAddressDetailsService basicCustAddressDetailsService;
    private final BasicProductParamService basicProductParamService;

    @ApiOperation(value = "合同信息查询")
    @PostMapping("/getContractInfo")
    public IResponse getContractInfo(@RequestBody CommissionCondition condition) {

        String camainId = condition.getId();//合同ID

        if(StringUtils.isEmpty(camainId)){
            return IResponse.fail("合同ID不能为空");
        }
        BasicMainInfo mainInfo = basicMainInfoService.getOne(Wrappers.<BasicMainInfo>lambdaQuery()
                        .eq(BasicMainInfo::getId, camainId)
                ,false
        );

        if(mainInfo==null){
            return IResponse.fail("合同信息不存在");
        }
        //根据合同号以及产品ID查询融资信息
        BasicFinancialAgreement basicFinancialAgreement = basicFinancialAgreementService.getOne(Wrappers.<BasicFinancialAgreement>lambdaQuery()
                        .eq(BasicFinancialAgreement::getContractNo, mainInfo.getContractNo())
                        .eq(BasicFinancialAgreement::getProductId, mainInfo.getProductId())
                ,false
        );
        //根据合同号查询车辆信息
        BasicCarDetails basicCarDetails = basicCarDetailsService.getOne(Wrappers.<BasicCarDetails>lambdaQuery()
                        .eq(BasicCarDetails::getContractNo, mainInfo.getContractNo())
                ,false
        );
        //查询主借人信息
        BasicContractCustRelation basicContractCustRelation = custRelationService.getOne(Wrappers.<BasicContractCustRelation>lambdaQuery()
                        .eq(BasicContractCustRelation::getContractNo, mainInfo.getContractNo())
                        .eq(BasicContractCustRelation::getCustRole, PersonRoleTypeEnum.MAIN_PERSON)
                ,false
        );
        JSONObject json = new JSONObject();
        //查询不同算法下不同的算法参数
        ProductAtomEnum[] productAtomArr = null;
        if(CalculateType.ballonloan.equals(basicFinancialAgreement.getAlgorithmType())){//分段贷还款计划
            productAtomArr = new ProductAtomEnum[]{ProductAtomEnum.BALLON_LOAN_TYPE, ProductAtomEnum.PEROIDS, ProductAtomEnum.MONEY};
        }
        if(CalculateType.structuredloan.equals(basicFinancialAgreement.getAlgorithmType())){//结构化还款
            productAtomArr = new ProductAtomEnum[]{ProductAtomEnum.STRUCTURED_MONTH, ProductAtomEnum.STRUCTURED_TYPE, ProductAtomEnum.STRUCTURED_MONEY};
        }
        if(CalculateType.equalratioret.equals(basicFinancialAgreement.getAlgorithmType())){//等比累进还款计划
            productAtomArr = new ProductAtomEnum[]{ProductAtomEnum.STEP, ProductAtomEnum.STE_PERCENT};
        }
        if(CalculateType.arbitraryloan.equals(basicFinancialAgreement.getAlgorithmType())){//任意贷还款计划
            productAtomArr = new ProductAtomEnum[]{ProductAtomEnum.PEROIDS, ProductAtomEnum.MONEY};
        }
        //将算法对应的数据新增进json
        if(productAtomArr!=null){
            json = this.getBasicProductParam(mainInfo.getContractNo(),mainInfo.getProductId(),json,productAtomArr);
        }
        //灵活贴息还款计划进行特殊处理
        if(CalculateType.flexiblediscount.equals(basicFinancialAgreement.getAlgorithmType())){
            json.put("discount",basicFinancialAgreement.getTotalDiscountAmt());//贴息总额
        }

        //创建返回值
        CommissionVo commissionVo = JSON.parseObject(json.toString(),CommissionVo.class);
        commissionVo.setId(camainId);//合同ID
        commissionVo.setApplicationNo(mainInfo.getApplyNo());//申请单号
        commissionVo.setContractNo(mainInfo.getContractNo());//合同号
        commissionVo.setActiveTime(DateUtil.formatDate(mainInfo.getStartDate()));//激活时间
        commissionVo.setDealerID(mainInfo.getChannelId()!=null?mainInfo.getChannelId().toString():null);//经销商
        commissionVo.setFinancialId(mainInfo.getProductId()!=null?mainInfo.getProductId().toString():null);//金融产品
        commissionVo.setFinancialName(mainInfo.getProductName());//金融产品名称
        commissionVo.setContractStatus(mainInfo.getContractStatus().name());//合同状态                  数据字典
        commissionVo.setCaseCategory(mainInfo.getBusinessType().name());//案件类别                      数据字典
        commissionVo.setLoanMoney(basicFinancialAgreement.getLoanAmt());//贷款金额
        commissionVo.setLoanPeriod(basicFinancialAgreement.getLoanTerm()!=null?basicFinancialAgreement.getLoanTerm().toString():null);//贷款期数
        commissionVo.setRate(basicFinancialAgreement.getCustRate());//客户利率
        commissionVo.setActualRate(basicFinancialAgreement.getSettleRate());//实际利率
        commissionVo.setFnType(basicFinancialAgreement.getAlgorithmType().name());//金融产品类型          数据字典
        commissionVo.setCommissionRatio(BigDecimal.ONE);//佣金比例,没有的字段默认传1
        commissionVo.setVehiclePrice(basicCarDetails.getGuidePrice());//车价
        commissionVo.setVehicleStyle(basicCarDetails.getModelCode());//车型
        commissionVo.setVin(basicCarDetails.getCarVin());//车架号
        commissionVo.setBrand(basicCarDetails.getBrandName());//品牌
        commissionVo.setBrandCode(basicCarDetails.getBrandCode());//品牌

        if(basicContractCustRelation!=null){
            //根据客户号查询主借人信息
            BasicCustBaseInfo basicCustBaseInfo = basicCustBaseInfoService.getOne(Wrappers.<BasicCustBaseInfo>lambdaQuery()
                            .eq(BasicCustBaseInfo::getCustNo, basicContractCustRelation.getCustNo())
                    ,false
            );
            if(basicCustBaseInfo!=null){
                commissionVo.setBorrower(basicCustBaseInfo.getCustName());//主借人
            }
            //查询主借人户籍地址
            BasicCustAddressDetails basicCustAddressDetails = basicCustAddressDetailsService.getOne(Wrappers.<BasicCustAddressDetails>lambdaQuery()
                            .eq(BasicCustAddressDetails::getCustNo, basicContractCustRelation.getCustNo())
                            .eq(BasicCustAddressDetails::getAddressType, AddressTypeEnum.HOME)
                    ,false
            );
            if(basicCustAddressDetails!=null){
                commissionVo.setProvince(basicCustAddressDetails.getProvince());//省份
                commissionVo.setCity(basicCustAddressDetails.getCity());//城市
            }
        }

        return IResponse.success(commissionVo);
    }

    //查询产品参数
    public JSONObject getBasicProductParam(String contractNo,Long productId,JSONObject json,ProductAtomEnum[] productAtomArr){
        for (int i = 0; i < productAtomArr.length; i++){
            ProductAtomEnum productAtomEnum = productAtomArr[i];
            BasicProductParam basicProductParam = basicProductParamService.getOne(Wrappers.<BasicProductParam>lambdaQuery()
                    .eq(BasicProductParam::getContractNo, contractNo)
                    .eq(BasicProductParam::getProductId, productId)
                    .eq(BasicProductParam::getAtomKey,AfsEnumUtil.key(productAtomEnum))
            );
            if(basicProductParam!=null){
                json.put( AfsEnumUtil.key(productAtomEnum),basicProductParam.getAtomValue());
            }
        }
        return json;
    }
}
